package com.health.teahouse.domain;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TEST {
    private static void buildTree(TreePojo item, Map<String, List<TreePojo>> treeMap) {
        // 使用hash的方式减少复杂度
        List<TreePojo> treeData = treeMap.get(item.getId());
        if (treeData != null) {
            item.setChildren(treeData);
            for (TreePojo treePojo : treeData) {
                buildTree(treePojo, treeMap);
            }
        }

    }



    public static void main(String[] args) {
        // 初始化数据
        List<TreePojo> treeData = new ArrayList<>();
        treeData.add(new TreePojo("1", "0", "根节点"));
        treeData.add(new TreePojo("2", "1", "父节点1"));
        treeData.add(new TreePojo("3", "1", "父节点2"));
        treeData.add(new TreePojo("4", "2", "子节点1"));
        treeData.add(new TreePojo("5", "2", "子节点2"));
// 转换为 key=pid value = pojo
//        Map<String, List<TreePojo>> treeMap = new HashMap<>();
//        for (TreePojo treeItem : treeData) {
//            List<TreePojo> treePojos = treeMap.computeIfAbsent(treeItem.getPid(), k -> new ArrayList<>());
//            treePojos.add(treeItem);
//        }
        Map<String, List<TreePojo>> treeMap = new HashMap<>();

        for (TreePojo treeItem : treeData) {
            String parentId = treeItem.getPid();

            List<TreePojo> treePojos = treeMap.get(parentId);
            if (treePojos == null) {
                treePojos = new ArrayList<>();
                treeMap.put(parentId, treePojos);
            }

            treePojos.add(treeItem);
        }

// 拿到根节点
        List<TreePojo> treePojos = treeMap.get("0");
        for (TreePojo treePojo : treePojos) {
            // 递归生成树结构
            buildTree(treePojo, treeMap);
        }
        System.out.println(treePojos);


    }
}
